Thread: Using "\r" with printf?

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    14

    Using "\r" with printf?

    Hi!

    I'm trying to print 4 lines with dinamic values without using "\n". Everyting works just fine when I use only one line. And the code is:

    Code:
    while (1){
    	num1=rand()%100;
    	num2=rand()%100;
    	num3=rand()%100;
    	num4=rand()%100;
    	printing(num1,num2,num3,num4);
    	usleep(500000);
    }
    
    void printing(int num1,int num2,int num3,int num4){
    	
    	fprintf(stderr,"\rActPos:\t%d\t%d\t%d\t%d",num1,num2,num3,num4);
    	fprintf(stderr,"\rOptPos:\t%d\t%d\t%d\t%d",num1,num2,num3,num4);
    	fprintf(stderr,"\rTrgPos:\t%d\t%d\t%d\t%d",num1,num2,num3,num4);
    	fprintf(stderr,"\rFlwErr:\t%d\t%d\t%d\t%d",num1,num2,num3,num4);
    
    }
    The way it is now it'll only print the last line an "update" it with new values.

    If i try to use "\n" before every "\r" the result is not what i expect because i only want to see 4 line in the command prompt with refreshed values every 0.5 seconds.

    What is the best way to accomplish my objective?
    Last edited by kovitch; 08-25-2008 at 10:49 AM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,334
    It's not possible in standard C to go "up" a line (you can write over the current line, but once you hit \n there's no going back). If you want to continually rewrite over the same real estate, you would need a graphics library (such as curses).

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    There are platform specific options or as tabstop recommended (and I concur with, for that matter) there is always the use of a graphics library.

    Perhaps you can use the carriage return character to return to the beginning of the current line and never print a newline. But just know that even doing that can look sloppy unless you are very thorough on how the output is generated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. making it portable.....?
    By ShadeS_07 in forum C Programming
    Replies: 11
    Last Post: 12-24-2008, 09:38 AM
  2. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  3. segmentation fault upon reload
    By yabud in forum C Programming
    Replies: 8
    Last Post: 12-18-2006, 06:54 AM
  4. Simple C question: user input to repeat a loop
    By evernaut in forum C Programming
    Replies: 2
    Last Post: 11-18-2006, 09:23 AM
  5. Drawing tables in C
    By stanoman in forum C Programming
    Replies: 5
    Last Post: 10-09-2003, 10:14 AM